#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/3/17 11:37
# @Author : hedan
# @FileName：index_collect_server.py
# @Software:PyCharm
import re
from datetime import datetime

from sqlalchemy import distinct, desc, func
from sqlalchemy import or_

from application import db
from application.libs import const, ymdhms_to_timestamp
from application.models.mantis_models import MantisBugTable, MantisProjectTable, MantisProjectVersionTable, \
    MantisBugHistoryTable, MantisUserTable, MantisCustomFieldStringTable
from application.models.models import VenusManti, ProjectRelevance, Collect
from application.models.venus_models import CdbTask, CdbTaskTime, CdbTaskLog0, CdbTaskLog1, CdbTaskLog2, \
    CdbTaskLog3, CdbTaskLog4, CdbTaskLog5, CdbTaskLog6, CdbTaskLog7, CdbTaskLog8, CdbTaskLog9

resqones_dict = {
    "pid": 'pro_id',
    "group": "group_name",  # 业务线
    "project": "project_name",  # 产品线
    "version": "version",  # 版本号
    "ptype": "demand_type",  # 需求类型
    "pstatus": 'status',  # 项目状态
    "begindate": "start_time",  # 开始时间
    "enddate": "end_time",  # 结束时间
    "onlinedate": "online_time",  # 上线时间
    "ticecount": "tice",  # 提测次数
    "anticecount": "ticeanshi",  # 按时提测次数
    "zhunrucount": "zhunru",  # 准入次数
    "zhunchucount": "zhunchu",  # 准出次数
    "anzhuchucount": "zhunchuanshi",  # 按时准出次数
    "casecount": "cheack",  # 检查点
    "maobugcount": 'smoke_bug',  # 冒烟bug数
    "fistbugcount": "frist_bug",  # 第一轮bug数
    "sumbugcount": "bug_sum",  # bug总数
    "spendtime": "dev_time",  # 研发工时
    "fixrate": "fix_rate",  # bug修复率
    "unfixrate": "unfix_rate",  # 无效修改率
    "onlinerate": "online_rate",  # 发布成功率
    # "relation": relation,  # 是否关联
    # "proproblem": "",  # 项目问题
    # "venusid": venusid,  # venusid
    #
    # "mantisid": mantisid,  # mantisid
    # "mantis": mantis,  # {'P1' : '10', 'P2' : '20', 'P3' : '30', 'P4' : '41', 'P5' : '100', 'reopen' : '14'}
    # "online": {"online_status": "", "onlineanshi": "", "online_count": '', "back": ''},  # {"是否上线": "", "是否按时上线": "", "上线次数": '', "回滚次数": ''}
    # "bug_Legacy": bug_Legacyy,  # {"未解决bug": '10', "bug总数": '192', "遗留bug数": '2'},
    # "pm_bug": {"use_bug": demandbug, "pm_fix": ""},  # {"用户体验/需求类问题数量": '10', "需求变更测试": '12'}
}


# 看板：一级目录
def venus_first_level(mgrop):
    '''
    看板：一级目录
    :param mgrop:
    :return:
    '''
    result = []
    if mgrop:
        comments = db.session.query(ProjectRelevance.venus_gname).filter(ProjectRelevance.venus_gname == mgrop).first()
        result.append({
            'group_name': comments[0]
        })
    else:
        comments = db.session.query(distinct(ProjectRelevance.venus_gname).label('venus_gname')).all()
        for i in comments:
            content = {

                'group_name': i.venus_gname
            }
            result.append(content)
    return result


def venus_two_level(groupname):
    '''
    看板：二级目录
    :param groupname:
    :return:
    '''
    comments = db.session.query(ProjectRelevance.venus_pname).filter(ProjectRelevance.venus_gname == groupname,
                                                                     ProjectRelevance.venus_pname != '0').all()
    result = []
    for i in comments:
        content = {
            'project_name': i.venus_pname
        }
        result.append(content)
    return result


def venus_three_level(venus_pname):
    '''
    看板：三级目录
    :param venus_pname:
    :return:
    '''
    comments = db.session.query(CdbTask.version).filter(CdbTask.category_product == venus_pname,
                                                        CdbTask.version != 'vundefined',
                                                        CdbTask.type != 'OnLine').order_by(desc('create_time')).all()
    result = []
    result.append({'version_name': '-'})
    for i in set(comments):
        content = {
            'version_name': i.version
        }
        result.append(content)
    return result


def mantis_first_level(vgoup):
    '''
    mantis：一级目录
    :param vgoup:
    :return:
    '''
    result = []
    if vgoup:
        comments = db.session.query(ProjectRelevance.mantis_gname).filter(
            ProjectRelevance.mantis_gname == vgoup).first()
        result.append({
            'group_name': comments[0]
        })
    else:
        comments = db.session.query(distinct(ProjectRelevance.mantis_gname).label('mantis_gname')).all()
        for i in comments:
            content = {
                'group_name': i.mantis_gname
            }
            result.append(content)
    return result


def mantis_two_level(groupname):
    '''
     mantis：二级目录
    :param groupname:
    :return:
    '''
    comments = db.session.query(ProjectRelevance.mantis_pname).filter(ProjectRelevance.mantis_gname == groupname,
                                                                      ProjectRelevance.mantis_pname != '0').all()
    result = []
    for i in comments:
        content = {
            'project_name': i.mantis_pname
        }
        result.append(content)
    return result


def mantis_three_level(mantis_pname):
    '''
    mantis：三级目录
    :param venus_pname:
    :return:
    '''
    comments = db.session.query(MantisProjectVersionTable.version).filter(MantisProjectVersionTable.project_id.in_(
        db.session.query(MantisProjectTable.id).filter(MantisProjectTable.name == mantis_pname))).order_by(
        desc('date_order')).all()
    result = []
    result.append({'version_name': '-'})
    for i in comments:
        content = {
            'version_name': i.version
        }
        result.append(content)
    return result


# 看板：根据项目获取对应项目id
def sel_venus_id(v_groupname, v_projectname, v_version):
    '''
    看板：根据项目获取对应项目id
    :param v_groupname:
    :param v_projectname:
    :param v_version:
    :return:
    '''
    comments = db.session.query(CdbTask.id).filter(CdbTask.category_business == v_groupname,
                                                   CdbTask.category_product == v_projectname,
                                                   CdbTask.version == v_version).all()
    return comments


def sel_mantis_id(name, vname):
    '''
    mantis：根据项目名称获取对应的项目id
    :param name:
    :param vname:
    :return:
    '''
    comments = db.session.query(MantisProjectVersionTable.id, MantisProjectVersionTable.project_id).join(
        MantisProjectTable,
        MantisProjectTable.id == MantisProjectVersionTable.project_id).filter(
        MantisProjectVersionTable.version == vname, MantisProjectTable.name == name).all()
    return comments


def get_project(v_groupname, v_projectname, v_version, m_projectname, m_version):
    result = []
    mantis_id, mantis_version_id = sel_mantis_id(v_projectname, v_version)[0]  # 查询mantis对应项目id
    version = v_version
    if mantis_id == []:
        mantis_id = sel_mantis_id(m_projectname, m_version)
        version = m_version
    venus_id = sel_venus_id(v_groupname, v_projectname, v_version)  # 查询看板对应项目id
    if venus_id:
        venusid = venus_id[0][0]
        dev_time = sel_develop_total(venusid)
    else:
        venusid = 0
        dev_time = ''
    if mantis_id:
        relation = True
        # insert_venus(stype, venus_id[0][0], mantis_id[0][0])
        mantiss = mantis(mantis_id, version)
        bug_Legacyy = bug_Legacy(mantis_id, version)
        demandbug = sel_demand_bug(mantis_id, version)
        maoyan = sel_maoyan(mantis_id, version)
        fistbug = sel_fistbug(mantis_id, version)
        fist = maoyan + fistbug
        re = sel_is_get_project(relation, mantis_id, mantiss, bug_Legacyy, demandbug, venusid,
                                mantis_version_id, maoyan, fist, dev_time)

        result.append(re)
    else:
        relation = False
        # 关联表中插入数据
        # insert_venus(stype, 0, 0)
        re = sel_not_get_project(relation)
        result.append(re)
    return result[0][0]


def sel_is_project(group, project, version):
    '''
    查询该条项目是否存在
    :param group:
    :param project:
    :param version:
    :return:
    '''
    comments = db.session.query(Collect.pid).filter(Collect.group == group, Collect.project == project,
                                                    Collect.version == version, Collect.status != 0).all()
    return comments


def get_save(data):
    '''
    添加修改
    :param data:
    :return:
    '''
    pid = data['project_info']["pro_id"]
    vgroup = data['pro_data']["v_group"]
    vproject = data['pro_data']["v_project"]
    vversion = data['pro_data']["v_version"]
    mgroup = data['pro_data']["m_group"]
    mproject = data['pro_data']["m_project"]
    mversion = data['pro_data']["m_version"]
    if isinstance(data['project_info']["demand_type"], int):
        ptype = str(data['project_info']["demand_type"])
    else:
        ptype = id_switch('demand_type', str(data['project_info']["demand_type"]))
    if isinstance(data['project_info']["status"], int):
        pstatus = data['project_info']["status"]
    else:
        pstatus = id_switch('status', str(data['project_info']["status"]))

    begindate = judge_data(data['project_info']["start_time"][:10])
    if data['project_info']["end_time"]:
        enddate = data['project_info']["end_time"][:10]
    else:
        enddate = None
    zhunchucount = judge_data(data['project_info']["zhunchu"])
    anzhuchucount = judge_data(data['project_info']["zhunchuanshi"])
    maobugcount = judge_data_int(data['project_info']["smoke_bug"])
    fistbugcount = judge_data_int(data['project_info']["frist_bug"])
    weibugcount = judge_data_int(data['project_info']["bug_Legacy"]['nofix_bug'])
    sumbugcount = judge_data_int(data['project_info']["bug_Legacy"]["sum_bug"])
    yiliubug = judge_data_int(data['project_info']["bug_Legacy"]["ago"])
    P1 = judge_data_int(data['project_info']["mantis"]['P1'])
    P2 = judge_data_int(data['project_info']["mantis"]["P2"])
    P3 = judge_data_int(data['project_info']["mantis"]["P3"])
    P4 = judge_data_int(data['project_info']["mantis"]["P4"])
    P5 = judge_data_int(data['project_info']["mantis"]["P5"])
    tiyanbug = judge_data_int(data['project_info']["pm_bug"]["use_bug"])
    changecount = judge_data_int(data['project_info']["pm_bug"]["pm_fix"])
    reopenbug = judge_data_int(data['project_info']["mantis"]["reopen"])
    onlinecount = judge_data_int(data['project_info']["online"]["online_count"])
    rollcount = judge_data_int(data['project_info']["online"]["back"])

    ticecount = data['project_info']["tice"]
    anticecount = data['project_info']["ticeanshi"]
    zhunrucount = data['project_info']["zhunru"]
    casecount = int(data['project_info']["cheack"])
    spendtime = float(data['project_info']["dev_time"])
    online = data['project_info']["online"]['online_status']
    isonline = int(data['project_info']["online"]["onlineanshi"])
    pquest = data["pquest"]
    remark = data["remark"]
    creater = data["creater"]
    if data['project_info']["online_time"]:
        onlinedate = data['project_info']["online_time"][:10]
    else:
        onlinedate = None
    try:
        bugrate = format((P1 * 3 + P2 * 2 + P3 * 1 + P4 * 0.5) / spendtime, '.4')
    except:
        bugrate = '--'
    try:
        fixrate = format((sumbugcount - weibugcount) / sumbugcount, '.4')
    except:
        fixrate = '--'
    try:
        unfixrate = format(reopenbug / sumbugcount, '.4')
    except:
        unfixrate = '--'
    try:
        onlinerate = format((onlinecount - rollcount) / onlinecount, '.4')
    except:
        onlinerate = '--'
    try:
        bugdensity = format((P1 + P2 + P3 + P4 + P5 + tiyanbug) / casecount, '.4')
    except:
        bugdensity = '--'
    dmchange = changecount
    dmcount = P5 + tiyanbug + changecount
    bugcount = yiliubug + P1 + P2 + P3 + P4 + P5 + tiyanbug
    # venusid = ''
    # mantisid = ''
    addtiem = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    # 根据看板业务+产品线+版本号查询venusid
    if vversion == '-':
        venusid = None
    else:
        v_id = sel_venus_id(vgroup, vproject, vversion)
        if v_id:
            venusid = v_id[0][0]
        else:
            venusid = None
    # 根据mantis业务线+产品线+版本号查询mantis
    if mversion == '-':
        mantisid = None
        project_id = None
        group = mgroup
        project = mproject
        version = mversion
    else:
        m_id = sel_mantis_id(mproject, mversion)
        if m_id:
            mantisid = m_id[0][0]
            project_id = m_id[0][1]
            group = mgroup
            project = mproject
            version = mversion
        else:
            mantisid = None
            project_id = None
            group = mgroup
            project = mproject
            version = mversion
    if pid != '0':
        # 有id编辑
        db.session.query(Collect).filter(Collect.pid == pid).update(
            {'ptype': ptype, 'pstatus': pstatus, 'begindate': begindate, 'enddate': enddate, 'ticecount': ticecount,
             'anticecount': anticecount, 'zhunrucount': zhunrucount, 'anzhuchucount': anzhuchucount,
             'casecount': casecount, 'maobugcount': maobugcount, 'fistbugcount': fistbugcount,
             'weibugcount': weibugcount, 'sumbugcount': sumbugcount, 'yiliubug': yiliubug, 'P1': P1, 'P2': P2,
             'P3': P3, 'P4': P4, 'P5': P5, 'tiyanbug': tiyanbug, 'changecount': changecount, 'reopenbug': reopenbug,
             'spendtime': spendtime, 'online': online, 'isonline': isonline, 'onlinecount': onlinecount,
             'rollcount': rollcount, 'pquest': pquest, 'remark': remark, 'addtiem': addtiem, 'bugrate': bugrate,
             'fixrate': fixrate,
             'unfixrate': unfixrate, 'onlinerate': onlinerate, 'bugdensity': bugdensity, 'dmchange': dmchange,
             'dmcount': dmcount, 'bugcount': bugcount, 'onlinedate': onlinedate, 'zhunchucount': zhunchucount})
    else:  # 没有id就新增
        # 判断该项目是否存在，存在更新，
        res = sel_is_project(group, project, version)
        if res:
            return group + "-" + project + "-" + version + "已经录入,请选择其他mantis项目版本！"
            # # 更新
            # db.session.query(Collect).filter(Collect.pid == res[0][0]).update(
            #     {'ptype': ptype, 'pstatus': pstatus, 'begindate': begindate, 'enddate': enddate, 'ticecount': ticecount,
            #      'anticecount': anticecount, 'zhunrucount': zhunrucount, 'anzhuchucount': anzhuchucount,
            #      'casecount': casecount, 'maobugcount': maobugcount, 'fistbugcount': fistbugcount,
            #      'weibugcount': weibugcount, 'sumbugcount': sumbugcount, 'yiliubug': yiliubug, 'P1': P1, 'P2': P2,
            #      'P3': P3, 'P4': P4, 'P5': P5, 'tiyanbug': tiyanbug, 'changecount': changecount, 'reopenbug': reopenbug,
            #      'spendtime': spendtime, 'online': online, 'isonline': isonline, 'onlinecount': onlinecount,
            #      'rollcount': rollcount, 'pquest': pquest, 'remark': remark, 'addtiem': addtiem, 'bugrate': bugrate,
            #      'fixrate': fixrate,
            #      'unfixrate': unfixrate, 'onlinerate': onlinerate, 'bugdensity': bugdensity, 'dmchange': dmchange,
            #      'dmcount': dmcount, 'bugcount': bugcount, 'onlinedate': onlinedate})
        else:
            # 添加
            insert = Collect(group=group, project=project, version=version,
                             v_group=vgroup, v_project=vproject, v_version=vversion, ptype=ptype, pstatus=pstatus,
                             begindate=begindate, enddate=enddate, ticecount=ticecount, anticecount=anticecount,
                             zhunrucount=zhunrucount, zhunchucount=zhunchucount, anzhuchucount=anzhuchucount,
                             casecount=casecount, maobugcount=maobugcount, fistbugcount=fistbugcount,
                             weibugcount=weibugcount, sumbugcount=sumbugcount, yiliubug=yiliubug, P1=P1, P2=P2, P3=P3,
                             P4=P4, P5=P5, tiyanbug=tiyanbug, changecount=changecount, reopenbug=reopenbug,
                             spendtime=spendtime, online=online, isonline=isonline, onlinecount=onlinecount,
                             rollcount=rollcount, pquest=pquest, remark=remark, venusid=venusid, mantisid=mantisid,
                             addtiem=addtiem,
                             bugrate=bugrate, fixrate=fixrate, unfixrate=unfixrate, onlinerate=onlinerate,
                             bugdensity=bugdensity, dmchange=dmchange, dmcount=dmcount, bugcount=bugcount, status=1,
                             onlinedate=onlinedate, project_id=project_id, creater_qa= creater)
            db.session.add(insert)
    # try:
    db.session.commit()
    message = const.OPERATE_SUCCESS
    # except:
    #     db.session.rollback()
    #     message = const.OPERATE_FAIL
    return message


def collectDateValue(collect_info, fieldStr, field):
    """
    判断时间参数进行赋值，是否入库以及更改
    :param collect_info:
    :param data:
    :return:
    """
    if field:
        collect_info[fieldStr] = judge_data(field[:10])
    return collect_info


def judge_data_int(value):
    """
    判断计算参数，为空不进行int转换
    :return:
    """
    if not value:
        return 0
    else:
        return int(value)


def judge_data(value):
    """
    判断计算参数，为空不进行int转换
    :return:
    """
    if not value:
        return 0
    else:
        return value


def get_update(pid):
    '''
    刷新功能
    :param pid:
    :param project_id:
    :param version:
    :return:
    '''
    res = db.session.query(Collect.spendtime, Collect.onlinecount, Collect.rollcount, Collect.casecount,
                           Collect.changecount, Collect.project_id, Collect.version, Collect.pstatus, Collect.venusid,
                           Collect.pstatus, Collect.status).filter(
        Collect.pid == pid).all()
    project_id = res[0][5]
    version = res[0][6]
    pstatus = res[0][9]
    status = res[0][10]
    if project_id and pstatus != '3' and status == 1:
        spendtime = res[0][0]
        if res[0][8]:
            developtime = float(sel_develop_total(res[0][8]))
            if developtime != 0:
                spendtime = developtime
        onlinecount = res[0][1]
        rollcount = res[0][2]
        casecount = res[0][3]
        changecount = res[0][4]
        ms = mantis(project_id, version)
        # for i in ms:
        #     P1 = int(i['P1'])
        #     P2 = int(i['P2'])
        #     P3 = int(i['P3'])
        #     P4 = int(i['P4'])
        #     P5 = int(i['P5'])
        #     reopenbug = int(i['reopen'])
        P1 = int(ms['P1'])
        P2 = int(ms['P2'])
        P3 = int(ms['P3'])
        P4 = int(ms['P4'])
        P5 = int(ms['P5'])
        reopenbug = int(ms['reopen'])
        bl = bug_Legacy(project_id, version)
        # for i in bl:
        #     weibugcount = int(i['weibug'])
        #     sumbugcount = int(i['sumbugcount'])
        #     yiliubug = int(i['yiliubug'])
        weibugcount = int(bl['nofix_bug'])
        sumbugcount = int(bl['sum_bug'])
        yiliubug = int(bl['ago'])
        tiyanbug = sel_demand_bug(project_id, version)
        maoyan = sel_maoyan(project_id, version)
        fistbug = sel_fistbug(project_id, version)
        fist = maoyan + fistbug
        try:
            bugrate = format((P1 * 3 + P2 * 2 + P3 * 1 + P4 * 0.5) / spendtime, '.2')
        except:
            bugrate = '--'
        try:
            fixrate = format((sumbugcount - weibugcount) / sumbugcount, '.2')
        except:
            fixrate = '--'
        try:
            unfixrate = format(reopenbug / sumbugcount, '.2')
        except:
            unfixrate = '--'
        try:
            onlinerate = format((onlinecount - rollcount) / onlinecount, '.2')
        except:
            onlinerate = '--'
        try:
            bugdensity = format((P1 + P2 + P3 + P4 + P5 + tiyanbug) / casecount, '.2')
        except:
            bugdensity = '--'
        # fixrate = format((sumbugcount - weibugcount) / sumbugcount, '.2')
        # unfixrate = format(reopenbug / sumbugcount, '.2')
        # onlinerate = format((onlinecount - rollcount) / onlinecount, '.2')
        # bugdensity = format((P1 + P2 + P3 + P4 + P5 + tiyanbug) / casecount, '.2')
        dmchange = changecount
        dmcount = P5 + tiyanbug + changecount
        bugcount = yiliubug + P1 + P2 + P3 + P4 + P5 + tiyanbug

        db.session.query(Collect).filter(Collect.pid == pid).update(
            {'P1': P1, 'P2': P2, 'P3': P3, 'P4': P4, 'P5': P5, 'reopenbug': reopenbug, 'weibugcount': weibugcount,
             'sumbugcount': sumbugcount, 'yiliubug': yiliubug, 'bugrate': bugrate, 'fixrate': fixrate,
             'unfixrate': unfixrate, 'onlinerate': onlinerate, 'bugdensity': bugdensity, 'dmchange': dmchange,
             'dmcount': dmcount, 'bugcount': bugcount, 'maobugcount': maoyan, 'fistbugcount': fist,
             'spendtime': spendtime})
        message = '刷新成功'
    else:
        message = '无法刷新'
    return message


def sel_severity_bug(project_id, vname, severity_id):
    '''
    bug率：不含用户体验、需求、之前版本遗留bug（不包含不必改、重复问题）
    根据mantis中project_id+版本号查询P1——P5的bug
    对应项目下p1级bug
    p1=80 p2=70 p3=60 p4=50 p5=10
    :param project_id:
    :param vname:
    :param severity_id:
    :return:
    '''
    comments = db.session.query(MantisBugTable).filter(MantisBugTable.project_id == project_id,
                                                       MantisBugTable.version == vname,
                                                       MantisBugTable.severity == severity_id,
                                                       MantisBugTable.category_id.notin_([6, 8]),
                                                       MantisBugTable.resolution.notin_([70, 60, 90]),
                                                       MantisBugTable.id.notin_(
                                                           db.session.query(MantisBugHistoryTable.bug_id).filter(
                                                               MantisBugHistoryTable.field_name == 'version'))).count()
    return comments


def sel_weijiejue_bug(project_id, vname):
    '''
    bug修复率：不含建议类、用户体验类
    未解决bug总数：
    :param project_id:
    :param vname:
    :return:
    '''
    comments = db.session.query(MantisBugTable).filter(MantisBugTable.project_id == project_id,
                                                       MantisBugTable.version == vname, MantisBugTable.status == 50,
                                                       MantisBugTable.category_id != 6, MantisBugTable.severity != 10,
                                                       MantisBugTable.resolution.notin_([60, 70, 90])).count()
    return comments


def sel_zongshu_bug(project_id, vname):
    '''
    bug总数
    :param project_id:
    :param vname:
    :return:
    '''
    comments = db.session.query(MantisBugTable).filter(MantisBugTable.project_id == project_id,
                                                       MantisBugTable.version == vname, MantisBugTable.category_id != 6,
                                                       MantisBugTable.severity != 10,
                                                       MantisBugTable.resolution.notin_([60, 70, 90])).count()
    return comments


def sel_yiliu_bug(project_id, vname):
    '''
    遗留bug数
    :param project_id:
    :param vname:
    :return:
    '''
    comments = db.session.query(MantisBugTable).filter(MantisBugTable.project_id == project_id,
                                                       MantisBugTable.version == vname, MantisBugTable.id.in_(
            db.session.query(MantisBugHistoryTable.bug_id).filter(MantisBugHistoryTable.field_name == 'version')),
                                                       MantisBugTable.category_id != 6, MantisBugTable.severity != 10,
                                                       MantisBugTable.resolution.notin_([60, 70, 90])).count()
    return comments


def sel_demand_bug(project_id, vname):
    '''
    需求类：不含之前版本遗留的bug
    用户体验及需求总数
    :param project_id:
    :param vname:
    :return:
    '''
    comments = db.session.query(MantisBugTable).filter(MantisBugTable.project_id == project_id,
                                                       MantisBugTable.version == vname,
                                                       MantisBugTable.category_id.in_([6, 8]),
                                                       MantisBugTable.resolution.notin_([60, 70, 90]),
                                                       MantisBugTable.id.notin_(
                                                           db.session.query(MantisBugHistoryTable.bug_id).filter(
                                                               MantisBugHistoryTable.field_name == 'version'))).count()

    return comments


def sel_reopen_bug(project_id, vname):
    '''
    reopen bug数量
    :param project_id:
    :param vname:
    :return:
    '''
    comments = db.session.query(MantisBugTable).join(MantisUserTable,
                                                     MantisBugTable.handler_id == MantisUserTable.id).filter(
        MantisBugTable.id.in_(
            db.session.query(MantisBugHistoryTable.bug_id).filter(MantisBugHistoryTable.new_value == 30)),
        MantisBugTable.project_id == project_id, MantisBugTable.version == vname).count()
    return comments


def mantis(project_id, vname):
    '''
    mantis bug率+需求类+无效修改率
    p1=80 p2=70 p3=60 p4=50 p5=10
    :param project_id:
    :param vname:
    :return:
    '''
    p1 = sel_severity_bug(project_id, vname, 80)
    p2 = sel_severity_bug(project_id, vname, 70)
    p3 = sel_severity_bug(project_id, vname, 60)
    p4 = sel_severity_bug(project_id, vname, 50)
    p5 = sel_severity_bug(project_id, vname, 10)
    reopenbug = sel_reopen_bug(project_id, vname)
    content = {
        'P1': p1,
        'P2': p2,
        'P3': p3,
        'P4': p4,
        'P5': p5,
        'reopen': reopenbug
    }
    return content


def id_switch(ty, id):
    '''
    转换id对应的类型及状态
    status(pstatus) = [
      { value: 1, label: '测试中' },
      { value: 2, label: '测试完成' },
      { value: 3, label: '已上线' }
    demand(ptype) = [
      { value: 1, label: '标准需求' },
      { value: 2, label: '验收需求' },
      { value: 3, label: '生产事故' },
      { value: 4, label: '线上bug' },
      { value: 5, label: '紧急发版' }
    ]
    :param ty:
    :param id:
    :return:
    '''
    if ty == 'status':
        d = {'测试中': '1', '测试完成': '2', '已上线': '3'}
        r = d[id]
    elif ty == 'demand_type':
        d = {'标准需求': '1', '验收需求': '2', '生产事故': '3', '线上bug': '4', '紧急发版': '5'}
        r = d[id]
    elif ty == 'pstatus':
        d = {'1': '测试中', '2': '测试完成', '3': '已上线'}
        r = d[id]
    elif ty == 'ptype':
        d = {'1': '标准需求', '2': '验收需求', '3': '生产事故', '4': '线上bug', '5': '紧急发版'}
        r = d[id]
    return r


def bug_Legacy(project_id, vname):
    '''
    bug_Legacy,bug修复率
    # p1=80 p2=70 p3=60 p4=50 p5=10
    :param project_id:
    :param vname:
    :return:
    '''

    weibug = sel_weijiejue_bug(project_id, vname)
    sumbugcount = sel_zongshu_bug(project_id, vname)
    yiliubug = sel_yiliu_bug(project_id, vname)
    content = {
        'nofix_bug': weibug,
        'sum_bug': sumbugcount,
        'ago': yiliubug
    }
    return content


def get_collect(pid):
    """
    项目详情
    :param case_querys: pid
    :return:
    """

    # 拼接查询条件
    try:
        project = db.session.query(Collect).filter(Collect.pid == int(pid), Collect.status != 0).one()
    except:
        return '未查询到此项目详情，请刷新后重试！'

    # pro_vm = db.session.query(ProjectRelevance).filter(ProjectRelevance.qa_gname == project.group,
    #                                                    ProjectRelevance.qa_pname == project.project).one()

    # textarea = '项目问题:\n' + (if project.)
    def _getpquest(pquest):
        if pquest is not None:
            return pquest
        else:
            return '无'

    def _getremark(remark):
        if remark is not None:
            return remark
        else:
            return '无'

    pro_data = {
        'v_group': project.v_group,
        'v_project': project.v_project,
        'v_version': project.v_version,
        'm_group': project.group,
        'm_project': project.project,
        'm_version': project.version
    }
    project_info = {
        "demand_type": id_switch('ptype', project.ptype),
        "status": id_switch('pstatus', project.pstatus),
        "start_time": project.begindate,
        "end_time": project.enddate,
        "online_time": project.onlinedate,
        "pro_id": project.pid,
        "mantis": {'P1': project.P1, 'P2': project.P2, 'P3': project.P3, 'P4': project.P4, 'P5': project.P5,
                   'reopen': project.reopenbug},
        "tice": project.ticecount,
        "ticeanshi": 1 == project.anticecount,
        "zhunru": project.zhunrucount,
        "zhunchu": project.zhunchucount,
        "zhunchuanshi": 1 == project.anzhuchucount,
        "cheack": project.casecount,
        "smoke_bug": project.maobugcount,
        "frist_bug": project.fistbugcount,
        "bug_Legacy": {"nofix_bug": project.weibugcount, "sum_bug": project.sumbugcount, "ago": project.yiliubug},
        "pm_bug": {"use_bug": project.tiyanbug, "pm_fix": project.changecount},
        "dev_time": project.spendtime,
        "online": {"online_status": 1 == project.online, "onlineanshi": 1 == project.isonline,
                   "online_count": project.onlinecount, "back": project.rollcount}
    }
    quality_data = {
        "bugrate": rate_swich(project.bugrate),
        "fixrate": rate_swich(project.fixrate),
        "unfixrate": rate_swich(project.unfixrate),
        "onlinerate": rate_swich(project.onlinerate),
        "bugdensity": rate_swich_bugdensity(project.bugdensity),
        "dmchange": project.dmchange,
        "dmcount": project.dmcount
    }
    relation = project.venusid is not None and project.mantisid is not None
    data = {
        "quality_data": quality_data,
        'pquest': _getpquest(project.pquest),
        'remark': _getremark(project.remark),
        'project_info': project_info,
        'relation': relation,
        'pro_data': pro_data
    }
    return data


def rate_swich(num):
    """
    百分比转换
    :param num:str （0.3211）
    :return:  -- or 32.11%
    """
    if '-' in num:
        return num
    elif '未上线' in num:
        return '--'
    else:
        return "%.2f%%" % (float(num) * 100)

def rate_swich_bugdensity(num):
    """
    转换-保留两位小数
    :param num:str （0.3211）
    :return:  -- or 32.11%
    """
    if '-' in num:
        return num
    elif '未上线' in num:
        return '--'
    else:
        return "%.2f" % (float(num))


def get_collect_list(collect_querys):
    """
    质量收集列表查询
    :param case_querys:
    :return:
    """
    # 拼接查询条件
    parm = []
    bugs = 0
    pr_parm = []
    if collect_querys['project_str'].strip() != '':  # 项目名称
        parm.append(or_(Collect.group.contains(collect_querys['project_str']),
                        Collect.project.contains(collect_querys['project_str']),
                        Collect.version.contains(collect_querys['project_str']))
                    )
    else:
        if collect_querys['group_name'] != '':  # 业务线
            # if collect_querys['group_name'] == '内容·运营':
            #     parm.append(or_(Collect.group == '互动',
            #                     Collect.group == '资讯')
            #                 )
            #     pr_parm.append(or_(ProjectRelevance.qa_gname == '互动',
            #                        ProjectRelevance.qa_gname == '资讯')
            #                    )
            # else:
            parm.append(Collect.group == collect_querys['group_name'])
            pr_parm.append(ProjectRelevance.qa_gname == collect_querys['group_name'])
            # bug情况

            pro_l = db.session.query(ProjectRelevance).filter(*pr_parm).all()
            mantis_id_list = [MantisBugTable.project_id == i.mantis_id for i in pro_l if i.mantis_id != '0']
            Bug_parm = []
            Bug_parm.append(or_(*mantis_id_list))
            if collect_querys['start_time'] and collect_querys['end_time']:
                collect_querys['start_time'] += ' 00:00:00'
                collect_querys['end_time'] += ' 23:59:59'
                Bug_parm.append(MantisBugTable.date_submitted >= ymdhms_to_timestamp(collect_querys['start_time']))
                Bug_parm.append(MantisBugTable.date_submitted <= ymdhms_to_timestamp(collect_querys['end_time']))
                bugs = db.session.query(MantisBugTable, func.count(1).label("bug_count")).filter(*Bug_parm).all()
                bugs = bugs[0].bug_count
        if collect_querys['project_name'].strip() != '':  # 项目
            parm.append(Collect.project == collect_querys['project_name'])
    if collect_querys['status'] != '':  # 项目状态
        parm.append(Collect.pstatus == collect_querys['status'])
    if collect_querys['demand_type'] != '':  # 项目需求类型
        parm.append(Collect.ptype == collect_querys['demand_type'])
    if collect_querys['start_time']:  # 起始时间
        e_date = collect_querys['end_time']
        s_date = collect_querys['start_time']
        parm.append(or_(Collect.begindate >= s_date, Collect.onlinedate >= s_date, Collect.enddate >= s_date))
        parm.append(or_(Collect.begindate <= e_date, Collect.onlinedate <= e_date, Collect.enddate <= e_date))
        # parm.append(Collect.onlinedate <= e_date)
    parm.append(Collect.status != 0)
    page_data = db.session.query(Collect).filter(*parm).order_by(Collect.onlinedate.desc()).paginate(
        page=collect_querys[const.PAGE_NUM],
        per_page=collect_querys[const.PAGE_PER], error_out=False)
    vm_data = db.session.query(VenusManti.pid).all()
    vm_data_l = [x[0] for x in vm_data]
    response_dic = {}
    response_list = []
    mantis_pro_id = []
    if page_data.items:
        for msg in page_data.items:
            response_dic['pro_id'] = msg.pid  # pid
            response_dic['group_name'] = msg.group  # 业务线
            response_dic['relation'] = msg.pid in vm_data_l  # 关联状态
            response_dic['project_name'] = msg.project  # 项目名
            response_dic['version'] = msg.version  # 版本号
            response_dic['demand_type'] = msg.ptype  # 需求类型 1：标准需求、2：验收需求、3：生产事故、4：线上bug、5：紧急发版
            response_dic['status'] = msg.pstatus  # 项目状态 1:测试中.2:测试完成,3:已上线
            response_dic['end_time'] = msg.enddate  # 结束时间
            response_dic['online_time'] = msg.onlinedate
            response_dic['bug_rate'] = rate_swich(msg.bugrate)  # bug率
            response_dic['fix_rate'] = rate_swich(msg.fixrate)  # bug修复率
            response_dic['unfix_rate'] = rate_swich(msg.unfixrate)  # 无效修改率
            response_dic['online_rate'] = rate_swich(msg.onlinerate)  # 发布成功率
            response_dic['bug_sum'] = msg.bugcount  # bug总数
            response_dic['creater'] = msg.creater_qa  # 创建人
            response_list.append(response_dic.copy())
            response_dic.clear()
    response_dic['items'] = response_list
    response_dic['total'] = page_data.total
    response_dic["bugs"] = bugs
    return response_dic


def delete_collect(id):
    """
    删除
    :param id:
    :return:
    """
    collect = db.session.query(Collect).filter(Collect.pid == id).first()
    msg = const.DELETE_FAIL
    if collect:
        db.session.query(Collect).filter(Collect.pid == id).update({"status": 0})
        try:
            db.session.commit()
            msg = const.DELETE_SUCCESS
        except:
            # 事務回滾
            db.session.rollback()
            msg = const.DELETE_FAIL
    return msg


# def sel_maoyan(project_id, vname):
#     '''
#     冒烟bug
#     :param project_id:
#     :param vname:
#     :return:
#     '''
#     comments = db.session.query(MantisBugTable).filter(MantisBugTable.project_id == project_id,
#                                                        MantisBugTable.version == vname,
#                                                        MantisBugTable.category_id.notin_([6, 8]),
#                                                        MantisBugTable.resolution.notin_([60, 70, 90]),
#                                                        MantisBugTable.id.in_(
#                                                            db.session.query(MantisCustomFieldStringTable.bug_id).filter(
#                                                                MantisCustomFieldStringTable.value == '冒烟'))).count()
#     return comments
def sel_maoyan(project_id, vname):
    '''
    冒烟bug
    :param project_id:
    :param vname:
    :return:
    '''
    comments = db.session.query(MantisBugTable).filter(MantisBugTable.project_id == project_id,
                                                       MantisBugTable.version == vname,
                                                       MantisBugTable.category_id.notin_([6, 8]),
                                                       MantisBugTable.resolution.notin_([60, 70, 90]),
                                                       MantisBugTable.id.notin_(
                                                           db.session.query(MantisBugHistoryTable.bug_id).filter(
                                                               MantisBugHistoryTable.field_name == 'version')),
                                                       MantisBugTable.id.in_(
                                                           db.session.query(MantisCustomFieldStringTable.bug_id).filter(
                                                               MantisCustomFieldStringTable.value == '冒烟'))).count()
    return comments


def sel_fistbug(project_id, vname):
    '''
    第一轮bug（首轮bug+冒烟bug）
    :param project_id:
    :param vname:
    :return:
    '''
    comments = db.session.query(MantisBugTable).filter(MantisBugTable.project_id == project_id,
                                                       MantisBugTable.version == vname,
                                                       MantisBugTable.category_id.notin_([6, 8]),
                                                       MantisBugTable.resolution.notin_([60, 70, 90]),
                                                       MantisBugTable.id.notin_(
                                                           db.session.query(MantisBugHistoryTable.bug_id).filter(
                                                               MantisBugHistoryTable.field_name == 'version')),
                                                       MantisBugTable.id.in_(
                                                           db.session.query(MantisCustomFieldStringTable.bug_id).filter(
                                                               MantisCustomFieldStringTable.value == '首轮测试'))).count()
    return comments


# def sel_fistbug(project_id, vname):
#     '''
#     第一轮bug（首轮bug+冒烟bug）
#     :param project_id:
#     :param vname:
#     :return:
#     '''
#     comments = db.session.query(MantisBugTable).filter(MantisBugTable.project_id == project_id,
#                                                        MantisBugTable.version == vname,
#                                                        MantisBugTable.category_id.notin_([6, 8]),
#                                                        MantisBugTable.resolution.notin_([60, 70, 90]),
#                                                        MantisBugTable.id.in_(
#                                                            db.session.query(MantisCustomFieldStringTable.bug_id).filter(
#                                                                MantisCustomFieldStringTable.value == '首轮测试'))).count()
#     return comments


def sel_is_get_project(relation, project_id, mantis, bug_Legacyy, demandbug, venusid, mantisid, maoyan, firstbug,
                       dev_time):
    '''
    自动查询数据-有关联
    :param relation:
    :param project_id:
    :param mantis:
    :param bug_Legacyy:
    :param demandbug:
    :param venusid:
    :param mantisid:
    :return:
    '''
    result = []
    res = {
        "pquest": '',
        "remark": '',
        "relation": relation,  # 是否关联
        "project_info": {
            "demand_type": "",  # 需求类型
            "status": 2,  # 项目状态
            "start_time": "",  # 开始时间
            "end_time": "",  # 结束时间
            "online_time": "",  # 上线时间
            "pro_id": project_id,  # project_id
            "mantis": mantis,  # {'P1' : '10', 'P2' : '20', 'P3' : '30', 'P4' : '41', 'P5' : '100', 'reopen' : '14'}
            "tice": "",  # 提测次数
            "ticeanshi": "",  # 按时提测次数
            "zhunru": "",  # 准入次数
            "zhunchu": "",  # 准出次数
            "zhunchuanshi": "",  # 按时准出次数
            "cheack": "",  # 检查点
            "smoke_bug": maoyan,  # 冒烟bug数
            "frist_bug": firstbug,  # 第一轮bug数
            "bug_Legacy": bug_Legacyy,  # {"未解决bug": '10', "bug总数": '192', "遗留bug数": '2'},
            "pm_bug": {"use_bug": demandbug, "pm_fix": ""},  # {"用户体验/需求类问题数量": '10', "需求变更测试": '12'}
            "dev_time": dev_time,  # 研发工时
            "online": {"online_status": "", "onlineanshi": "", "online_count": '', "back": ''},
            # {"是否上线": "", "是否按时上线": "", "上线次数": '', "回滚次数": ''}
            "bug_sum": "",  # bug总数
            "venusid": venusid,  # venusid
            "mantisid": mantisid  # mantisid
        }
    }
    result.append(res)
    return result


def sel_not_get_project(relation=False):
    '''
    自动查询数据-无关联
    :param relation:
    :return:
    '''
    result = []
    res = {
        "pquest": '',
        "remark": '',
        "relation": relation,  # 是否关联
        "project_info": {
            "demand_type": "",  # 需求类型
            "status": "",  # 项目状态
            "start_time": "",  # 开始时间
            "end_time": "",  # 结束时间
            "online_time": "",  # 上线时间
            "pro_id": "",  # project_id
            "mantis": {'P1': '', 'P2': '', 'P3': '', 'P4': '', 'P5': '', 'reopen': ''},
            # {'P1' : '10', 'P2' : '20', 'P3' : '30', 'P4' : '41', 'P5' : '100', 'reopen' : '14'}
            "tice": "",  # 提测次数
            "ticeanshi": "",  # 按时提测次数
            "zhunru": "",  # 准入次数
            "zhunchu": "",  # 准出次数
            "zhunchuanshi": "",  # 按时准出次数
            "cheack": "",  # 检查点
            "smoke_bug": "",  # 冒烟bug数
            "frist_bug": "",  # 第一轮bug数
            "bug_Legacy": {"nofix_bug": '', "sum_bug": '', "ago": ''},
            # {"未解决bug": '10', "bug总数": '192', "遗留bug数": '2'},
            "pm_bug": {"use_bug": '', "pm_fix": ""},  # {"用户体验/需求类问题数量": '10', "需求变更测试": '12'}
            "dev_time": "",  # 研发工时
            "online": {"online_status": "", "onlineanshi": "", "online_count": '', "back": ''},
            # {"是否上线": "", "是否按时上线": "", "上线次数": '', "回滚次数": ''}
            "bug_sum": "",  # bug总数
            "venusid": "",  # venusid
            "mantisid": ""  # mantisid
        }
    }
    result.append(res)
    return result


def sel_develop_total(taskid):
    '''
    获取总工时
    :param taskid:
    :return:
    '''

    if taskid % 10 == 0:
        devetime = db.session.query(CdbTaskLog0.content).filter(CdbTaskLog0.task_id == taskid,
                                                                CdbTaskLog0.type == 'develop').first()
    if taskid % 10 == 1:
        devetime = db.session.query(CdbTaskLog1.content).filter(CdbTaskLog1.task_id == taskid,
                                                                CdbTaskLog1.type == 'develop').first()
    if taskid % 10 == 2:
        devetime = db.session.query(CdbTaskLog2.content).filter(CdbTaskLog2.task_id == taskid,
                                                                CdbTaskLog2.type == 'develop').first()
    if taskid % 10 == 3:
        devetime = db.session.query(CdbTaskLog3.content).filter(CdbTaskLog3.task_id == taskid,
                                                                CdbTaskLog3.type == 'develop').first()
    if taskid % 10 == 4:
        devetime = db.session.query(CdbTaskLog4.content).filter(CdbTaskLog4.task_id == taskid,
                                                                CdbTaskLog4.type == 'develop').first()
    if taskid % 10 == 5:
        devetime = db.session.query(CdbTaskLog5.content).filter(CdbTaskLog5.task_id == taskid,
                                                                CdbTaskLog5.type == 'develop').first()
    if taskid % 10 == 6:
        devetime = db.session.query(CdbTaskLog6.content).filter(CdbTaskLog6.task_id == taskid,
                                                                CdbTaskLog6.type == 'develop').first()
    if taskid % 10 == 7:
        devetime = db.session.query(CdbTaskLog7.content).filter(CdbTaskLog7.task_id == taskid,
                                                                CdbTaskLog7.type == 'develop').first()
    if taskid % 10 == 8:
        devetime = db.session.query(CdbTaskLog8.content).filter(CdbTaskLog8.task_id == taskid,
                                                                CdbTaskLog8.type == 'develop').first()
    if taskid % 10 == 9:
        devetime = db.session.query(CdbTaskLog9.content).filter(CdbTaskLog0.task_id == taskid,
                                                                CdbTaskLog9.type == 'develop').first()
    if devetime:
        comments = re.sub("\D", "", devetime[0])
    else:
        comments = db.session.query(CdbTaskTime.develop_total).filter(CdbTaskTime.task_id == taskid).all()
        if comments:
            comments = comments[0][0]
        else:
            comments = 0
    return comments


def get_project_all_info(havedata):
    pro_data = get_pro_data(havedata)
    mantis_s = {"P1": '', "P2": '', "P3": '', "P4": '', "P5": '', "reopen": ''}
    bug_Legacy_s = {"nofix_bug": '', "sum_bug": '', "ago": ''}
    pm_bug = ''
    fist = ''
    dev_time = ''
    maoyan = ''
    mantis_id = None
    venusid = None
    have_ll = [i for i in havedata if havedata[i] != '']
    if 'm_version' in have_ll:
        if havedata['m_version'] == '-':
            mantis_s = {"P1": '0', "P2": '0', "P3": '0', "P4": '0', "P5": '0', "reopen": '0'}
            bug_Legacy_s = {"nofix_bug": '0', "sum_bug": '0', "ago": '0'}
            pm_bug = '0'
            fist = '0'
            maoyan = '0'
        else:
            smi = sel_mantis_id(havedata['m_project'], havedata['m_version'])
            if smi:
                mantis_version_id, mantis_id = smi[0]
                mantis_s = mantis(mantis_id, havedata['m_version'])
                bug_Legacy_s = bug_Legacy(mantis_id, havedata['m_version'])
                pm_bug = sel_demand_bug(mantis_id, havedata['m_version'])
                maoyan = sel_maoyan(mantis_id, havedata['m_version'])
                fistbug = sel_fistbug(mantis_id, havedata['m_version'])
                fist = maoyan + fistbug
            else:
                mantis_s = {"P1": '0', "P2": '0', "P3": '0', "P4": '0', "P5": '0', "reopen": '0'}
                bug_Legacy_s = {"nofix_bug": '0', "sum_bug": '0', "ago": '0'}
                pm_bug = '0'
                fist = '0'
                maoyan = '0'

    if 'v_version' in have_ll:
        if havedata['v_version'] == '-':
            dev_time = '0'
        else:
            venus_id = sel_venus_id(havedata['v_group'], havedata['v_project'], havedata['v_version'])  # 查询看板对应项目id
            if venus_id == []:
                pass
            else:
                venusid = venus_id[0][0]
                dev_time = sel_develop_total(venusid)

    relation = venusid is not None and mantis_id is not None
    sizeForm = {
        'pro_data': pro_data[0],
        'sizeForm': {
            'pro_data': pro_data[1],
            'mantis': mantis_s,
            'bug_Legacy': bug_Legacy_s,
            'smoke_bug': maoyan,
            'pm_bug': {"use_bug": pm_bug, "pm_fix": ''},
            'frist_bug': fist,
            'dev_time': dev_time,
            'relation': relation
        }
    }
    return sizeForm


def vm_group(group):
    '''
    看板：一级目录
    :param mgrop:
    :return:
    '''
    result = []
    Collect_parm = []
    Collect_parm.append(or_(ProjectRelevance.venus_gname == group,
                            ProjectRelevance.mantis_gname == group)
                        )
    comments = db.session.query(ProjectRelevance.venus_gname, ProjectRelevance.venus_gname).filter(
        *Collect_parm).first()
    return comments[0], comments[1]


def vm_project(project):
    '''
    看板：2级目录
    :param mgrop:
    :return:
    '''
    result = []
    Collect_parm = []
    Collect_parm.append(or_(ProjectRelevance.venus_pname == project,
                            ProjectRelevance.mantis_pname == project)
                        )
    comments = db.session.query(ProjectRelevance.venus_pname, ProjectRelevance.mantis_pname).filter(
        *Collect_parm).first()
    return comments[0], comments[1]


def get_pro_data(pro_dict):
    pro_data = {'venvOptions': {}, 'mantisOptions': {}}
    froms_pro_data = pro_dict.copy()
    have_l = [i for i in pro_dict if pro_dict[i] != '']

    if 'v_project' in have_l or 'm_project' in have_l:
        if 'v_project' in have_l:
            project = pro_dict['v_project']
        else:
            project = pro_dict['m_project']

        froms_pro_data['v_project'], froms_pro_data['m_project'] = vm_project(project)
        venus_three = venus_three_level(froms_pro_data['v_project'])
        mantis_three = mantis_three_level(froms_pro_data['m_project'])
        pro_data['venvOptions']['v_version'] = venus_three
        pro_data['mantisOptions']['m_version'] = mantis_three

        if len(venus_three) == 1:
            froms_pro_data['v_version'] = venus_three[0]['version_name']

        if len(mantis_three) == 1:
            froms_pro_data['m_version'] = mantis_three[0]['version_name']
        if len(venus_three) == 0:
            froms_pro_data['v_version'] = '-'
        if len(mantis_three) == 0:
            froms_pro_data['m_version'] = '-'

    elif 'v_group' in have_l or 'm_group' in have_l:
        if 'm_group' in have_l:
            group = pro_dict['m_group']
        else:
            group = pro_dict['v_group']

        froms_pro_data['v_group'], froms_pro_data['m_group'] = vm_group(group)
        mantis_two = mantis_two_level(group)
        venus_two = venus_two_level(group)
        pro_data['mantisOptions']['m_project'] = mantis_two
        pro_data['venvOptions']['v_project'] = venus_two

    return pro_data, froms_pro_data


def verification_collect_version(data):
    """
    判断是否已经关联过
    :param data:
    :return:
    """
    parm = [Collect.status == 1]
    if data["v_group"] and data["v_project"] and data["v_version"]:
        parm.append(Collect.v_group == data["v_group"])
        parm.append(Collect.v_project == data["v_project"])
        parm.append(Collect.v_version == data["v_version"])
    if data["m_group"] and data["m_project"] and data["m_version"]:
        parm.append(Collect.group == data["m_group"])
        parm.append(Collect.project == data["m_project"])
        parm.append(Collect.version == data["m_version"])
    if len(parm) == 1:
        return True
    page_data = db.session.query(Collect).filter(*parm).all()
    if page_data:
        return False
    else:
        return True
